/**
 * Created by apple on 16/3/17.
 */
import './style.scss'
import template from './menuCreate.view.html';
import viewController from './menuCreate.controller';

class Controller {
    constructor (systemService, $stateParams, $uiModal, uiNotification) {
        "ngInject"
        this.notify      = uiNotification;
        this.service     = systemService;
        this.uiModal     = $uiModal;
        this.currentNode = null;
        this.child       = true;
        this.treeData    = {};
        this.compData    = {};
        this.cache       = {};
        this.createItem  = false;
        // 获取归属平台列表
        systemService.getPlat().then(res => {
            this.platList = res.data;
        });
    }

    toggleConfirm (item) {
        item.confirm = !item.confirm
    }

    deleteNode (type, item) {
        type = angular.isNumber(type) ? 'comp' : 'menu';
        let param = type == 'menu' ? {menuId: item.id} : {compId: item.id};
        let pid = type == 'menu' ? item.parMenuId : item.menuId;
        this.service.delItem(type, param).then(() => {
            let idx = _.findIndex(this.cache[pid], param);
            this.cache[pid].splice(idx,1);
            if (!this.cache[pid].length) {
                if (type == 'menu') {
                    this.node.hasChildren = false;
                }
            }
            this.notify.success({
                'title'  : '提示',
                'message': '操作成功!'
            });
        }).catch((data) => {
            this.notify.error({
                'title'  : '提示',
                'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
            });
        })
    }

    renderTree (node, overwrite) {
        let typeId = node.compId ? node.compId : node.menuId;
        if ( this.node.hasChildren || this.node.hadComp ) {
            if ( this.cache[ typeId ] ) {
                node.nodes    = this.cache[ typeId ];
                overwrite && (this.menuList = this.cache[ typeId ]);
                return;
            }
            node.loading            = true;
            this.treeData.parMenuId = node.menuId;
            // 请求子菜单
            this.service.getTree('menuComp', this.treeData).then((res)=> {
                // this.ok = true;
                __DEBUG__ && console.log(res)
                this.cache[ typeId ] = res.data;
                node.nodes                = this.cache[ typeId ];
                // 点击菜单名称的时候, 才渲染数据列表
                overwrite && (this.menuList = this.cache[ typeId ]);
            }).catch((data) => {
                this.notify.error({
                    'title'  : '提示',
                    'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
                });
            }).finally(function () {
                node.loading = false;
            });
        } else {
            this.cache[ this.parentOrgId ] = [];
            this.menuList                  = this.cache[ this.parentOrgId ];
            this.child                     = false;
        }
    }

    selectNode (scope, node) {

        if (node.compId) return;

        let treePoints = [];
        let $parent    = scope.$nodeScope.$parentNodeScope;
        let $node      = scope.$nodeScope;
        // 生成路径信息
        treePoints.push($node.$modelValue.menuName);
        if ( $parent ) {
            let tempNode = $parent;
            tempNode.$element.removeClass('active');
            while ( tempNode ) {
                tempNode.$element.find('.active').removeClass('active')
                treePoints.push(tempNode.$modelValue.menuName)
                tempNode = tempNode.$parentNodeScope
            }
            this.currentNode = treePoints.reverse().join('<i class="fa fa-angle-right"></i>')
        } else {
            $node.$element.find('.active').removeClass('active');
            this.currentNode = $node.$modelValue.menuName
        }
        $node.$element.addClass('active');
        this.node = node;
        this.parentOrgId = node.menuId;
        this.renderTree(node, 1);
        __DEBUG__ && console.log(this.cache)
    }

    toggleNode (scope, node, $event) {
        if (node.compId) return;
        $event.preventDefault();
        // 生成路径信息
        let treePoints = [];
        let $parent    = scope.$nodeScope.$parentNodeScope;
        let $node      = scope.$nodeScope;
        treePoints.push(scope.$nodeScope.$modelValue.menuName);
        if ( $parent ) {
            let tempNode = $parent;
            while ( tempNode ) {
                treePoints.push(tempNode.$modelValue.menuName);
                tempNode = tempNode.$parentNodeScope
            }
            this.currentNode = treePoints.reverse().join('<i class="fa fa-angle-right"></i>')
        } else {
            this.currentNode = $node.$modelValue.menuName
        }
        this.node = node;
        this.parentOrgId = node.menuId;
        if ( scope.collapsed ) {
            scope.expand();
            this.renderTree(node)
        } else {
            scope.collapse();
        }
    }

    openView (type, item) {
        if (type) {
            if (!angular.isString(type)) {
                type = angular.isNumber(type) ? 'comp' : 'menu';
            }
        } else {
            type = 'menu'
        }

        if ( this.parentOrgId == null ) {
            return this.notify.warning({
                'title'  : '提示',
                'message': '请选择父级节点!'
            });
        }
        let modalInstance = this.uiModal.open({
            animation   : true,
            templateUrl : template,
            controller  : viewController,
            controllerAs: 'vm',
            size        : 'md',
            resolve     : {
                node: () => {
                    return {
                        item   : item,
                        type   : type,
                        pid    : this.parentOrgId,
                        sysCode: this.treeData.sysCode
                    }
                }
            }
        });

        // 处理对话框提交/关闭
        modalInstance.result.then((res) => {
            __DEBUG__ && console.log(res)
            if (item) {
                let param = type == 'menu' ? {menuId: res.id} : {compId: res.id};
                let idx = _.findIndex(this.cache[this.parentOrgId], param);
                this.cache[this.parentOrgId][idx] = res;
            } else {
                if (type == 'menu') {
                    this.node.hasChildren = true;
                    this.cache[this.parentOrgId].unshift(res)
                } else {
                    this.node.hasComp = true;
                    this.cache[this.parentOrgId].push(res)
                }
                this.node.nodes = this.cache[this.parentOrgId];
            }
        });
    }

    onSelected (item) {
        if ( this.isTreeLoading ) return;
        this.isTreeLoading      = true;
        this.treeData.parMenuId = 0;
        this.treeData.sysCode   = item.platSysNbr;
        this.compData.menuId    = null;
        this.currentNode        = item.platName;
        this.service.getTree('menuComp', this.treeData).then(res => {
            this.isTreeLoading = false;
            this.cache = {
                0 : res.data
            };
            this.menuList = [];
            this.compList = [];
            this.treeNode = [];
            this.treeNode.push({ menuName: item.platName, menuId: 0, nodes: res.data, hasChildren: true });
        })
    }

}
export default Controller;